//
//  DR_HomeHeaderView.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/10.
//

import UIKit

class DR_HomeHeaderView: UIView {
    
    // 回调：选中图片后返回图片数组
    var onImagesSelected: (([UIImage]) -> Void)?
    var functionBlock: ((Int) -> Void)?
    var selBlock: (() -> Void)?
    
    private let dataSource: [DR_HomeFunctionModel] = [
        
        DR_HomeFunctionModel(iconName: "home_image", title: "home_image".localized),
        DR_HomeFunctionModel(iconName: "home_merge", title: "home_merge".localized),
        DR_HomeFunctionModel(iconName: "home_splite", title: "home_split".localized),
        DR_HomeFunctionModel(iconName: "home_lock", title: "home_lock".localized),
        DR_HomeFunctionModel(iconName: "home_unlock", title: "home_unlock".localized)
    ]

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(titleLabel)
        addSubview(collectionView)
        addSubview(recentLabel)
        addSubview(selButton)
        
        titleLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(24)
            make.height.equalTo(28)
        }
        collectionView.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview().offset(-15)
            make.top.equalTo(titleLabel.snp.bottom).offset(20)
            make.height.equalTo(300)
        }
        recentLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(15)
            make.top.equalTo(collectionView.snp.bottom).offset(22)
            make.height.equalTo(21)
        }
        selButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-15)
            make.centerY.equalTo(recentLabel)
            make.height.width.equalTo(24)
        }
    }
    
    private let titleLabel: UILabel = {
        let v = UILabel()
        v.text = "home_title".localized
        v.textColor = .black
        v.font = UIFont.systemFont(ofSize: 24, weight: .bold)
        return v
    }()
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.sectionInset = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
        
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .clear
        cv.showsVerticalScrollIndicator = false
        cv.layer.cornerRadius = 26
        cv.layer.maskedCorners = [.layerMaxXMinYCorner,.layerMaxXMaxYCorner]
        cv.layer.masksToBounds = true
        cv.backgroundColor = "#333FFF".toColor
        cv.delegate = self
        cv.dataSource = self
        cv.register(DR_HomeFunctionCell.self, forCellWithReuseIdentifier: DR_HomeFunctionCell.identifier)
        
        return cv
    }()
    private let recentLabel: UILabel = {
        let v = UILabel()
        v.text = "home_recent".localized
        v.textColor = .black
        v.font = UIFont.systemFont(ofSize: 18, weight: .bold)
        return v
    }()
    private let selButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage("home_recent".toImage, for: .normal)
        v.addTarget(self, action: #selector(clickSelButton), for: .touchUpInside)
        return v
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 打开图片选择器
    private func presentImagePicker() {
        guard let viewController = getCurrentViewController() else {
            print("⚠️ [DR_HomeHeaderView] 无法获取当前 ViewController")
            return
        }
        
        DR_ImagePickerTool.shared.presentPhotoPicker(from: viewController) { [weak self] images in
            self?.onImagesSelected?(images)
        }
    }
    
    @objc private func clickSelButton(){        
        selBlock?()
    }
    
    // MARK: - 获取当前 ViewController
    private func getCurrentViewController() -> UIViewController? {
        var responder: UIResponder? = self
        while responder != nil {
            responder = responder?.next
            if let viewController = responder as? UIViewController {
                return viewController
            }
        }
        return nil
    }
}

// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension DR_HomeHeaderView: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DR_HomeFunctionCell.identifier, for: indexPath) as! DR_HomeFunctionCell
        cell.configure(with: dataSource[indexPath.item])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        
        if indexPath.row == 0 {
            // Image To PDF 功能
            presentImagePicker()
        }else{
            functionBlock?(indexPath.row)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        let inter = layout.minimumInteritemSpacing
        let columns: CGFloat = 3
        let width = (collectionView.bounds.width - 45 - inter * (columns - 1)) / columns
        return CGSize(width: floor(width), height: 128)
    }
}



struct DR_HomeFunctionModel {
    let iconName: String
    let title: String
}

class DR_HomeFunctionCell: UICollectionViewCell {
    
    static let identifier = "DR_HomeFunctionCell"
    
    private let containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 20
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowOffset = CGSize(width: 0, height: 2)
        view.layer.shadowRadius = 4
        view.layer.shadowOpacity = 0.1
        return view
    }()
    
    private let iconImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()
    
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        label.textColor = .black
        label.numberOfLines = 0
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(containerView)
        containerView.addSubview(iconImageView)
        containerView.addSubview(titleLabel)
        
        containerView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        iconImageView.snp.makeConstraints { make in
            make.leading.top.equalToSuperview().offset(6)
            make.width.height.equalTo(55)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(iconImageView.snp.bottom).offset(15)
            make.left.right.equalToSuperview().inset(12)
        }
    }
    
    func configure(with model: DR_HomeFunctionModel) {
        iconImageView.image = UIImage(named: model.iconName)
        titleLabel.text = model.title
    }
}
